package com.ljt.common.security.service;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.ljt.admin.dto.UserInfo;
import com.ljt.admin.entity.SysUser;
import com.ljt.admin.feign.RemoteUserService;
import com.ljt.common.constant.CommonConstants;
import com.ljt.common.constant.SecurityConstants;
import com.ljt.common.security.util.UserUtils;
import com.ljt.common.utils.BaseResult;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;


/**
 * @author administrator
 * @date 2019/07/25
 */
@Slf4j
@Service
@AllArgsConstructor
public class CloudUserDetailsServiceImpl implements UserDetailsService {
	private final RemoteUserService remoteUserService;
	private final CacheManager cacheManager;

	/**
	 * 用户密码登录
	 *
	 * @param username 用户名
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		Cache cache = cacheManager.getCache("user_details");
		if (cache != null && cache.get(username) != null) {
			return (CloudUser) cache.get(username).get();
		}

		BaseResult<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
		UserDetails userDetails = UserUtils.getUserDetails(result);
		cache.put(username, userDetails);
		return userDetails;
	}


}
